<?php

namespace App\Datas;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Tools\Curl;

class UserGoogleSubscribe
{
    protected $curl;

    public function __construct()
    {
        $this->curl = new Curl();
    }

    /**
     * @desc 新增用户订阅
     */ 
    public static function subscrlbe($userId, $productId, $packageName, $purchaseToken, $orderId) 
    {
        $insertData = [
            'user_id' => $userId,
            'product_id' => $productId,
            'package_name' => $packageName,
            'purchase_token' => $purchaseToken,
            'order_id' => $orderId
        ];

        DB::table('user_google_subscribe')->insert($insertData);
    }

    /**
     * @desc 生成临时密钥
     */ 
    private static function signAssertion()
    {
        $header = [
            'alg' => 'RS256',
            'typ' => 'JWT',
        ];
        $claims = [
            'iss' => 'web-server@api-4810948583920337310-536357.iam.gserviceaccount.com',
            'scope' => 'https://www.googleapis.com/auth/androidpublisher',           // 订阅功能授权地址
            'aud' => 'https://www.googleapis.com/oauth2/v4/token',
            'exp' => time() + 3600,  // 1小时内有效
            'iat' => time(),
        ];

        $header = json_encode($header);
        $header = base64_encode($header);

        $claims = json_encode($claims);
        $claims = base64_encode($claims);

        $signature = $header . '.' . $claims;
        $private_key = "-----BEGIN PRIVATE KEY-----私钥-----END PRIVATE KEY-----";
        $assertion = "";
        $algo = "SHA256";
        openssl_sign($signature, $assertion, $private_key, $algo);
        $assertion = base64_encode($assertion);

        return $header . '.' . $claims . '.' . $assertion;
    }

    /**
     * @desc 向google请求临时授权token
     */ 
    private static function getToken()
    {
        if (!file_exists('token.txt')) {
            requestTokenFromGoogle();
        } else {
            $time = filemtime('token.txt');
            $minutes = ceil((time() - $time) / 60);

            if ($minutes > 59) {
                requestTokenFromGoogle();
            }
        }

        $token = file_get_contents('token.txt');

        return $token;
    }

    private static function requestTokenFromGoogle()
    {
        $data = array(
            'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'assertion' => signAssertion()
        );
        
        $result = curl_post_https('https://www.googleapis.com/oauth2/v4/token', http_build_query($data));
        $result = json_decode($result, true);
        $token = $result['access_token'];
        
        file_put_contents('token.txt', $token, FILE_USE_INCLUDE_PATH);
    }

    private static function curl_post_https($url,$data){
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回

        $tmpInfo = curl_exec($curl); // 执行操作

        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }

        curl_close($curl); // 关闭CURL会话

        return $tmpInfo; // 返回数据，json格式
    }

    /**
     * @desc 向google请求用户订阅信息
     */ 
    public function getUserSubscribeStatus($packageName, $productId, $purchaseToken)
    {
        $packageName = "com.jxfq.dalle";
        $productId = 'abc_123';
        $purchaseToken = "jaaddemohpbjodhccmbpejjk.AO-J1OzkbGehkJDcmFwIP9m87XgNPWOZUp7kG_VJFfWIxxOICN0Iush-ac-_pLWYjinbf1HFw2Kqjzd1avGVSRojcJkIaNdE_w";
        $token = "22222";

        // $token = self::getToken();
        //token里面空格需要转译
        $purchaseToken = str_replace(' ', '%20', $purchaseToken);

        //注意参数
        // $url = 'https://www.googleapis.com/androidpublisher/v2/applications/' .
        //     "{$packageName}" . '/purchases/subscriptions/' . "{$productId}" .
        //     '/tokens/' . "{$purchaseToken}" . '?access_token=' . "{$token}";
        $url = 'https://www.googleapis.com/androidpublisher/v2/applications/' .
            "{$packageName}" . '/purchases/subscriptions/' . "{$productId}" .
            '/tokens/' . "{$purchaseToken}";

        $requestRes = $this->curl->curl_request($url, ['access_token' => $token], 'urlencoded', 'GET');
        echo '<pre>';
        print_r($requestRes);
        die;

        // $ch = curl_init($url);
        // curl_setopt($ch, CURLOPT_HEADER, false);
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // $result = curl_exec($ch);
        // curl_close($ch);

        return json_decode($result, true);
    }
}